import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    console.log(mutation, 'mutation', state)
    localStorage.setItem('state', JSON.stringify(state))
  })
}

export default new Vuex.Store({
  state: {
    // 需求：在登陆页面存储token; 在其他页面使用token.
    token: JSON.parse(localStorage.getItem('state'))?.token || '',
    homeList: [],
    cartList: JSON.parse(localStorage.getItem('state'))?.cartList || [],
    total: 0,
    list: [],
    myActive: 0,
  },
  plugins: [myPlugin],
  // 逻辑全部在mutation这个地方这个地方
  mutations: {
    set_myActive(state, active) {
      state.myActive = active
    },
    set_list_item(state, item) {
      state.list.push(item)
    },
    set_token(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    set_list(state, { list, total }) {
      // state.list.push(item)
      state.homeList = list
      state.total = total
    },
    to_cart(state, item) {
      // 去重复
      const goods = state.cartList.find((v) => v.id === item.id)
      if (goods) {
        goods.count++
      } else {
        item.count = 1
        state.cartList.push(item)
      }
    },
    add_item(state, item) {
      item.count++
    },
    remove_item(state, item) {
      if (item.count <= 1) {
        if (window.confirm('删除？')) {
          const removeIndex = state.cartList.findIndex((v) => v.id === item.id)
          state.cartList.splice(removeIndex, 1)
        }
        return
      }
      item.count--
    },
  },
  actions: {
    async fetchCartList({ commit }) {
      const res = await axios.get('/api/list')
      console.log('vuex=;list:', res.data.data)
      commit('set_list', {
        list: res.data.data.list,
        total: res.data.data.total,
      })
    },
  },
  getters: {},
  modules: {},
})
